package com.paradise.phone.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.paradise.api.FacephonePreferences;
import com.paradise.phone.R;
import com.paradise.phone.bean.UpdateInfo;
import com.paradise.phone.utils.ToastUtil;
import com.paradise.phone.utils.UpdateManager;

public class SettingFragment extends Fragment implements CompoundButton.OnCheckedChangeListener {

    private View rootView;

    private CheckBox cbAutoAcceptVideo;
    private CheckBox cbAutoStartCall;
    private CheckBox cbDefaultVideoCall;

    private TextView tvVersionUpdate;
    private TextView tvQuestion;
    private TextView tvVersionName;
    private TextView tvSwitchEncode;
    private TextView tvEncodeType;
    private ImageView ivNavigation;
    private DrawerLayout dlNavigation;
    private String result = null;
    private UpdateManager manager;
    private int choosedItem = 0;

    public SettingFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_setting, container, false);

        initView();

        initDate();

        initEvent();

        return rootView;
    }

    private void initView(){
        cbAutoAcceptVideo = (CheckBox) rootView.findViewById(R.id.cb_auto_accept_video);
        cbAutoStartCall = (CheckBox) rootView.findViewById(R.id.cb_auto_accept_call);
        cbDefaultVideoCall = (CheckBox) rootView.findViewById(R.id.cb_default_video_call);
        tvQuestion = (TextView) rootView.findViewById(R.id.tv_question);
        tvVersionUpdate = (TextView) rootView.findViewById(R.id.tv_version_update);
        ivNavigation = (ImageView) rootView.findViewById(R.id.iv_toolbar_navigation);
        dlNavigation = (DrawerLayout) getActivity().findViewById(R.id.navigation);
        tvVersionName = (TextView) rootView.findViewById(R.id.tv_version);
        tvSwitchEncode = rootView.findViewById(R.id.tv_switch_encode);
        tvEncodeType = rootView.findViewById(R.id.tv_encode_type);

        cbAutoAcceptVideo.setChecked(FacephonePreferences.instance().shouldAutomaticallyAcceptVideoRequests());
        cbAutoStartCall.setChecked(FacephonePreferences.instance().isAutoAnswerEnabled());
        cbDefaultVideoCall.setChecked(FacephonePreferences.instance().shouldInitiateVideoCall());

        showEncodeType();
    }

    private void initDate(){
        PackageManager manager = getActivity().getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = manager.getPackageInfo(getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        tvVersionName.setText("当前版本v"+packageInfo.versionName);

        tvSwitchEncode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int encodeType = FacephonePreferences.instance().getVideoEncode();
                switch (encodeType){
                    case 2:
                        choosedItem = 0;
                        break;
                    case 1:
                        choosedItem = 1;
                        break;
                    case 5:
                        choosedItem = 2;
                        break;
                }
                new AlertDialog.Builder(getActivity())
                        .setTitle("设置编码格式")
                        /*.setMessage("如果通话过程中本地预览黑屏，请更换编码格式尝试")*/
                        .setSingleChoiceItems(new CharSequence[]{"软编", "CPU硬编", "专业摄像头硬编"},
                                choosedItem, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        choosedItem = which;
                                    }
                                })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (choosedItem){
                                    case 0:
                                        FacephonePreferences.instance().setVideoEncode(2);
                                        break;
                                    case 1:
                                        FacephonePreferences.instance().setVideoEncode(1);
                                        break;
                                    case 2:
                                        FacephonePreferences.instance().setVideoEncode(5);
                                        break;
                                }
                                showEncodeType();
                            }
                        })
                        .show();
            }
        });
    }

    private void initEvent(){
        cbAutoAcceptVideo.setOnCheckedChangeListener(this);
        cbAutoStartCall.setOnCheckedChangeListener(this);
        cbDefaultVideoCall.setOnCheckedChangeListener(this);
        tvVersionUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(getActivity(), "开始检测版本更新");
                manager = UpdateManager.getInstance(getActivity());
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        result = manager.getUpdateInfo("http://123.207.47.49/paradise/updateinfo.json");
                        mHandler.sendEmptyMessage(0);
                    }
                }.start();
            }
        });
        ivNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!dlNavigation.isDrawerOpen(Gravity.LEFT)){
                    dlNavigation.openDrawer(Gravity.LEFT);
                }
            }
        });
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Gson gson = new Gson();
            Log.d("flag->", "SettingFragment.java(handleMessage:108)->"+result);
            final UpdateInfo info = gson.fromJson(result, UpdateInfo.class);
            if (manager.isNeedUpdate(info)){
                new AlertDialog.Builder(getActivity())
                        .setTitle("检测到新版本")
                        .setMessage("版本号："+info.getVersionName()+"\n更新内容："+info.getDescription())
                        .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                manager.downLoadAPK(info.getDownloadUrl());
                            }
                        })
                        .setNegativeButton("忽略", null)
                        .show();

            }else {
                ToastUtil.showToast(getActivity(), "已经是最新版本");
            }
        }
    };

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_auto_accept_call:
                FacephonePreferences.instance().enableAutoAnswer(isChecked);
                break;

            case R.id.cb_auto_accept_video:
                FacephonePreferences.instance().setAutomaticallyAcceptVideoRequests(isChecked);
                break;

            case R.id.cb_default_video_call:
                FacephonePreferences.instance().setInitiateVideoCall(isChecked);
                break;

        }
    }

    private void showEncodeType(){
        int encodeType = FacephonePreferences.instance().getVideoEncode();
        switch (encodeType){
            case 2:
                tvEncodeType.setText("软编");
                break;
            case 1:
                tvEncodeType.setText("CPU硬编");
                break;
            case 5:
                tvEncodeType.setText("专业摄像头硬编");
                break;
        }
    }
}
